package org.rockyang.shardingjdbc.base.algorithm.db;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;
import org.rockyang.shardingjdbc.base.exception.BizException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author: zhenwq
 * @Date: 2023/4/12
 * @Description:
 */
@Slf4j
public class DbHintShardingAlgorithm implements HintShardingAlgorithm<Integer> {

    public DbHintShardingAlgorithm() {
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, HintShardingValue<Integer> hintShardingValue) {
        log.info("当前存在库有:" + collection);
        log.info("传入的参数列表:" + JSON.toJSONString(hintShardingValue));

        // hint传参
        Collection<Integer> hintValueCollection = hintShardingValue.getValues();
        if(CollectionUtil.isEmpty(hintValueCollection)){
            throw new BizException("hint-DB传参为空");
        }
        List<String> result = new ArrayList<>();
        Integer dbHintNum = new ArrayList<>(hintValueCollection).get(0);
        List<String> dbList = new ArrayList<>(collection);
        for (String dbName : dbList) {
            String dbNum = dbName.substring(dbName.length() - 1);
            if(dbNum.equals(String.valueOf(dbHintNum))){
                result.add(dbName);
            }
        }
        log.info("分库路由结果:"+JSON.toJSONString(result));
        return result;
    }

}
